import json
from datetime import datetime

from django.db.models import Q
from django.http import JsonResponse

from lapi_app.models.user_model.user_info import Userinfo
from lapi_app.view.user_view.token_check import access_token


def edit_user(request):
    body = request.body
    data = json.loads(body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    account = data["account"]
    if "id" not in data.keys():
        if Userinfo.objects.filter(username=data["username"]).exists():
            return JsonResponse({"code": 100, "message": "创建用户失败,用户名已存在"})
        else:
            Userinfo.objects.create(account=account, username=data["username"], password=data["password"],
                                    email=data["email"], email_password=data["email_password"])
            return JsonResponse({
                "code": 200,
                "message": "创建用户成功"
            })
    else:
        if Userinfo.objects.filter(~Q(id=data["id"]), username=data["username"]).exists():
            return JsonResponse({"code": 100, "message": "编辑用户失败，账号已存在"})
        else:
            Userinfo.objects.filter(id=data["id"]) \
                .update(account=account, username=data["username"], email=data["email"],
                        email_password=data["email_password"], update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            return JsonResponse({
                "code": 200,
                "message": "编辑用户成功",
                "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            })


def get_userinfo(request):
    data = json.loads(request.body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    user_id = data["id"]
    users = Userinfo.objects.filter(id=user_id)
    result = []
    for user in users:
        user_dict = {
            "account": user.account,
            "username": user.username,
            "email": user.email,
            "email_password": user.email_password,
        }
        result.append(user_dict)
    return JsonResponse({
        "code": 200,
        "message": "获取用户信息成功",
        "content": result
    })


def edit_password(request):
    data = json.loads(request.body)
    if not access_token(data["user_id"]):
        return JsonResponse({
            "code": 1001,
            "message": "登录失效，请重新登录"
        })
    user_id = data["id"]
    users = Userinfo.objects.filter(id=user_id)
    original_password = data["original_password"]
    confirm_password = data["confirm_password"]
    try:
        for user in users:
            if original_password == user.password:
                Userinfo.objects.filter(id=user_id). \
                    update(password=confirm_password, update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                return JsonResponse({
                    "code": 200,
                    "message": "修改密码成功"
                })
            else:
                return JsonResponse({
                    "code": 100,
                    "message": "原密码错误，请重新输入"
                })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": "修改密码失败",
            "Exception": str(e)
        })


def user_all(request):
    users = Userinfo.objects.all()
    result = []
    for i in users:
        user_dict = {
            "user_id": i.id,
            "username": i.username
        }
        result.append(user_dict)
    return JsonResponse({
        "code": 200,
        "content": result
    })